package com.xh.generate.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 * @Name GenerateUtil
 * @Description freemarker文件到处工具类
 * @Date 2019年2月19日
 * @Author wen
 */
public class GenerateUtil {

    private static Configuration configuration;

    /**
     * 默认字符编码
     */
    private static final String EXPORT_ENCODING = "UTF-8";

    /**
     * 模板存放路径
     */
    private static final String TEMPLETE_PATH = "/templates";

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setDefaultEncoding(EXPORT_ENCODING);
        configuration.setClassForTemplateLoading(GenerateUtil.class, TEMPLETE_PATH);
//        try {
//            configuration.setDirectoryForTemplateLoading(new File(Thread.currentThread()
//                    .getContextClassLoader()
//                    .getResource(TEMPLETE_PATH)
//                    .getPath()));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    /**
     * @param templeteName 模板文件名
     * @return
     * @throws Exception
     * @Name getTemplate
     * @Description 获取模板
     * @Date 2019年2月19日
     * @Author wen
     */
    private static Template getTemplate(String templeteName) throws Exception {
        return configuration.getTemplate(templeteName + ".ftl");
    }

    /**
     * @param savePath     保存的doc文档全路径
     * @param templeteName 模板文件名
     * @param data
     * @throws Exception
     * @Name export
     * @Description 导出doc文档
     * @Date 2019年2月19日
     * @Author wen
     */
    public static void export(String savePath, String templeteName, Map<String, Object> data) throws IOException {
        Writer writer = null;
        FileOutputStream fileOutputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            fileOutputStream = new FileOutputStream(savePath);
            outputStreamWriter = new OutputStreamWriter(fileOutputStream, EXPORT_ENCODING);
            writer = new BufferedWriter(outputStreamWriter);
            getTemplate(templeteName).process(data, writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
            if (outputStreamWriter != null) fileOutputStream.close();
            if (fileOutputStream != null) fileOutputStream.close();
        }
    }

}